<template>
  <el-upload
    v-model:file-list="fileList"
    action="#"
    list-type="picture-card"
    :limit="field.limit"
    accept="image/*"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-exceed="handleExceed"
    :http-request="httpRequest"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type {
  UploadProps,
  UploadUserFile,
  UploadRequestOptions
} from "element-plus";
import { FormField } from "../utils";

interface Props {
  modelValue: string[];
  field: FormField;
}

interface Emits {
  (e: "update:modelValue", value: string[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePreview: UploadProps["onPreview"] = uploadFile => {
  console.log(uploadFile);

  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleRemove: UploadProps["onRemove"] = uploadFile => {
  const index = fileList.value.indexOf(uploadFile);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }
};

const handleExceed: UploadProps["onExceed"] = files => {
  ElMessage.warning(
    `The limit is ${props.field.limit}, you selected ${files.length} files this time, add up to ${
      files.length + fileList.value.length
    } totally`
  );
};

const httpRequest = (options: UploadRequestOptions) => {
  emit("update:modelValue", [
    ...fileList.value.map(el => el.url),
    URL.createObjectURL(options.file)
  ]);
  return Promise.resolve({});
};
</script>
